package org.leviatan.common.encoding;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;

import org.apache.commons.codec.binary.Base64;

public abstract class Base64Manager {
	
	private static BufferedInputStream bis;
	
	private static FileInputStream fis;
	
	private static FileOutputStream fos;
	
	private static BufferedOutputStream bos;
	
	
	
	
	public static void encode(String fromFile, String toFile) {
		byte[] encBytes = Base64Manager.encode(fromFile);
		Base64Manager.writeFile(toFile, encBytes);	
	}
	
	public static byte[] encodeString(String stringToEncode) {
		return Base64Manager.encode(stringToEncode.getBytes());
	}
	
	public static byte[] decodeString(String stringToDecode) {
		return Base64Manager.decode(stringToDecode.getBytes());
	}
	
	public static byte[] decode(byte[] bytesToDecode) {
		return Base64.decodeBase64(bytesToDecode);
	}
	
	public static byte[] encode(String fromFile) {
		return Base64.encodeBase64(Base64Manager.readFile(fromFile));
	}
	
	public static byte[] encode(byte[] fromByteArray) {
		return Base64.encodeBase64(fromByteArray);
	}
	
	private static void writeFile(String theFiletoWrite, byte[] theData) {
		
		try {
			
			Base64Manager.fos = new FileOutputStream(theFiletoWrite);
			Base64Manager.bos = new BufferedOutputStream(Base64Manager.fos);
			
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		}
		
		try {
			bos.write(theData);
			bos.flush();
			bos.close();
			fos.close();
			
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		
	}
	
	private static byte[] readFile(String theFileToRead) {
		
		try {
			
			Base64Manager.fis = new FileInputStream(theFileToRead);
			Base64Manager.bis = new BufferedInputStream(Base64Manager.fis);
			
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		}
		
		Vector v = new Vector();
		int nextByte;
		int counter = 0;
		
		try {
			while (true) {
				nextByte = bis.read();
				if (nextByte == -1)
					break;
				v.add(counter, new Byte((byte) nextByte));
				counter++;
			}
			
			Base64Manager.fis.close();
			Base64Manager.bis.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] byteArray = new byte[counter];
		
		// copy from vector into byte array
		for (int i = 0; i < counter; i++) {
			Byte b = (Byte) v.get(i);
			byteArray[i] = b.byteValue();
		}
		
		return byteArray;
	}

}
